package com.zhouyibike.uu.ui.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.entity.PayForRegisterResult;
import com.zhouyibike.uu.entity.PayResult;
import com.zhouyibike.uu.entity.SettingResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.web.TotalWebActivity;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.utils.TextUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class YanzhengActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private ImageView iv_renzheng;
    private ImageButton mBtnBack;
    private TextView mBtnTitle;
    private TextView tv_dot1, tv_dot2;
    private LinearLayout ll_paymsg;
    private LinearLayout ll_idmsg;
    private LinearLayout ll_khf;
    private EditText et_name, et_idnum, et_yanzheng_city;
    private CheckBox cb_wx, cb_zfb;
    private String paytype = "1";//默认
    private Button btn_sure;
    private IWXAPI api;
    private TextView tv_khmoney, tv_agreement;
    private TextView jindutoptv;
    private ImageView jindutopiv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yanzheng);
        api = WXAPIFactory.createWXAPI(this, null);
        EventBus.getDefault().register(this);
        initView();
        getSettings();
    }

    private void initView() {
        tv_agreement = (TextView) findViewById(R.id.tv_agreement);
        tv_agreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getWZMsg();
            }
        });
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnBack.setOnClickListener(this);
        et_yanzheng_city = (EditText) findViewById(R.id.et_yanzheng_city);
        et_yanzheng_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(YanzhengActivity.this, CityoActivity.class);
                startActivityForResult(i, 200);
            }
        });
        iv_renzheng = (ImageView) findViewById(R.id.iv_yanzheng_renzheng);
        tv_dot1 = (TextView) findViewById(R.id.tv_yanzheng_dot1);
        tv_dot2 = (TextView) findViewById(R.id.tv_yanzheng_dot2);
        ll_paymsg = (LinearLayout) findViewById(R.id.ll_yanzheng_paymsg);
        ll_idmsg = (LinearLayout) findViewById(R.id.ll_yanzheng_idmsg);
        ll_khf = (LinearLayout) findViewById(R.id.ll_yanzheng_khf);
        btn_sure = (Button) findViewById(R.id.btn_yanzheng_sure);
        jindutoptv= (TextView) findViewById(R.id.jindutoptv);
        jindutopiv= (ImageView) findViewById(R.id.jindutopiv);
        tv_agreement.setVisibility(View.GONE);
        if (preferences.getString("status", "").equals("0")) {//缴费
            mBtnTitle.setText("骑行充值");
            iv_renzheng.setImageResource(R.mipmap.yanzheng_weishiming);
            ll_paymsg.setVisibility(View.VISIBLE);
            ll_idmsg.setVisibility(View.GONE);
            ll_khf.setVisibility(View.VISIBLE);
            jindutoptv.setText("骑行充值");
            jindutopiv.setImageResource(R.mipmap.yanzhengkaihu);
//            tv_agreement.setVisibility(View.VISIBLE);
        } else {
            jindutopiv.setImageResource(R.mipmap.yanzheng_yishiming);
            jindutoptv.setText("实名认证");
            mBtnTitle.setText("实名认证");
            iv_renzheng.setImageResource(R.mipmap.yanzheng_yishiming);
            tv_dot1.setTextColor(getResources().getColor(R.color.color_normal));
            ll_paymsg.setVisibility(View.GONE);
            ll_idmsg.setVisibility(View.VISIBLE);
            ll_khf.setVisibility(View.GONE);
            btn_sure.setText("立即认证");
            tv_agreement.setVisibility(View.GONE);
        }
        cb_wx = (CheckBox) findViewById(R.id.cb_yanzheng_wx);
        cb_wx.setOnCheckedChangeListener(this);
        cb_zfb = (CheckBox) findViewById(R.id.cb_yanzheng_zfb);
        cb_zfb.setOnCheckedChangeListener(this);
        btn_sure.setOnClickListener(this);
        et_name = (EditText) findViewById(R.id.et_yanzheng_name);
        et_idnum = (EditText) findViewById(R.id.et_yanzheng_idnum);
        et_name.addTextChangedListener(new EditTextWatcher());
        et_idnum.addTextChangedListener(new EditTextWatcher());
        tv_khmoney = (TextView) findViewById(R.id.tv_yanzheng_kfmoney);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.btn_yanzheng_sure:
//                initresultDailog(true);
//                resultdialog.show();
                if (!preferences.getBoolean("hasPassword", false)) {//设置支付密码
                    initDailog();
                    yzmdialog.show();
                } else {
                    if (preferences.getString("status", "").equals("0")) {//缴费
                        monipay();
                    } else {
                        if (TextUtils.isNullorEmpty(et_name.getText().toString())) {
                            toastShow("请输入姓名");
                            return;
                        }
                        if (TextUtils.isNullorEmpty(et_idnum.getText().toString())) {
                            toastShow("请输入身份证号码");
                            return;
                        }
                        if (TextUtils.isNullorEmpty(et_yanzheng_city.getText().toString())) {
                            toastShow("请选择城市");
                            return;
                        }
                        idyanzheng();
                    }
                }
                break;
        }
    }

    private Dialog yzmdialog;

    /**
     * 支付密码设置dialog
     */
    private void initDailog() {
        View view = LayoutInflater.from(this).inflate(
                R.layout.yanzheng_dialog, null);
        yzmdialog = new Dialog(this, R.style.loading_dialog);
        final EditText et_name = (EditText) view.findViewById(R.id.et_yanzhengdialog_name);
        final EditText et_idnum = (EditText) view.findViewById(R.id.et_yanzhengdialog_idnum);
//        et_name.addTextChangedListener(new EditTextWatcher1());
//        et_idnum.addTextChangedListener(new EditTextWatcher2());
        Button btn_sure = (Button) view.findViewById(R.id.btn_yanzhengdialog_sure);
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isNullorEmpty(et_name.getText().toString()) && TextUtils.isNullorEmpty(et_idnum.getText().toString())) {
                    toastShow("请输入完整信息");
                } else if (!et_name.getText().toString().equals(et_idnum.getText().toString())) {
                    toastShow("两次输入密码不一致");
                } else {
                    if (et_name.getText().toString().length() < 6 || et_idnum.getText().toString().length() < 6) {
                        toastShow("请将密码设置为6位数字");
                    } else {
                        setzfnum(et_name.getText().toString());
                    }
                }
            }
        });
        ImageView iv_dismis = (ImageView) view.findViewById(R.id.iv_codedialog_dismis);
        iv_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yzmdialog.dismiss();
            }
        });
        yzmdialog.setContentView(view, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        yzmdialog.setCancelable(true);
        yzmdialog.setCanceledOnTouchOutside(false);
        yzmdialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

    private Dialog resultdialog;
    DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                return true;
            } else {
                return false;
            }
        }
    };

    /**
     * 认证结果dialog
     */
    private void initresultDailog(boolean issuccess) {
        View view = LayoutInflater.from(this).inflate(
                R.layout.yz_result_dialog, null);
        resultdialog = new Dialog(this, R.style.loading_dialog);
        TextView tv_title = (TextView) view.findViewById(R.id.tv_yzresultdailog_title);
        ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_yzresultdailog_pic);
        Button btn_sure = (Button) view.findViewById(R.id.btn_yzresultdailog_sure);
        if (issuccess) {
            tv_title.setText("认证成功");
            tv_title.setTextColor(getResources().getColor(R.color.color_normal));
            iv_pic.setImageResource(R.mipmap.renzheng_success);
            btn_sure.setText("立即用车");
            btn_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    resultdialog.dismiss();
                    setResult(1);
                    finish();
                }
            });
        } else {
            tv_title.setText("认证失败");
            tv_title.setTextColor(getResources().getColor(R.color.text_main_3));
            iv_pic.setImageResource(R.mipmap.renzheng_fail);
            btn_sure.setText("重新认证");
            btn_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    resultdialog.dismiss();
                }
            });
        }

        ImageView iv_dismis = (ImageView) view.findViewById(R.id.iv_codedialog_dismis);
        iv_dismis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resultdialog.dismiss();
            }
        });
        resultdialog.setContentView(view, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        resultdialog.setCancelable(true);
        resultdialog.setCanceledOnTouchOutside(false);
        resultdialog.setOnKeyListener(keylistener);
        resultdialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }

    //设置支付密码
    private void setzfnum(String paynum) {
        Map<String, String> params = new HashMap<>();
        params.put("password", paynum);
        params.put("mobile", preferences.getString("mobile", ""));
        params.put("sign", TextUtils.MD5(preferences.getString("mobile", "") + preferences.getString("appKey", "")));
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.SetPasswrod(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putBoolean("hasPassword", true);
                            edit.commit();
                            yzmdialog.dismiss();
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    private String px() {
        String px = "";
        List<String> list = new ArrayList<String>();
        list.add(et_idnum.getText().toString().trim());
        list.add(et_name.getText().toString().trim());
        list.add(preferences.getString("appKey", "").trim());
        Collections.sort(list, new MapComparator());
        for (String person : list) {
            px = px + person;
        }
        return px;
    }

    class MapComparator implements Comparator<String> {

        public int compare(String lhs, String rhs) {
            return lhs.compareTo(rhs);
        }

    }

    /**
     * 实名认证
     */
    private void idyanzheng() {
        Map<String, String> params = new HashMap<>();
        params.put("name", et_name.getText().toString().trim());
        params.put("idCard", et_idnum.getText().toString().trim());
//        params.put("sign", TextUtils.MD5(et_name.getText().toString()+preferences.getString("appKey",""))+et_idnum.getText().toString());
        params.put("agencyLocation", et_yanzheng_city.getText().toString().trim());
        params.put("sign", TextUtils.MD5(px()));
        params.put("token", preferences.getString("token", "").trim());
        showProgressDialog();
        addSubscription(apiStores.Approve(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            setResult(1);
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putString("status", "3");
                            edit.commit();
                            initresultDailog(true);
                            resultdialog.show();
                        } else {
                            toastShow(model.getMessage());
                            initresultDailog(false);
                            resultdialog.show();
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    /**
     * 支付成功后更改界面状态
     */
    private void paysuccesschangestate() {
        SharedPreferences.Editor edit = preferences.edit();
        edit.putString("status", "1");
        edit.commit();
        mBtnTitle.setText("实名认证");
        iv_renzheng.setImageResource(R.mipmap.yanzheng_yishiming);
        tv_dot1.setTextColor(getResources().getColor(R.color.color_normal));
        btn_sure.setText("立即认证");
        btn_sure.setEnabled(false);
        ll_paymsg.setVisibility(View.GONE);
        ll_idmsg.setVisibility(View.VISIBLE);
        ll_khf.setVisibility(View.GONE);
        jindutopiv.setImageResource(R.mipmap.yanzheng_yishiming);
        jindutoptv.setText("实名认证");
    }

    private void getSettings() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.GetSettings(params),
                new ApiCallback<SettingResult>() {

                    @Override
                    public void onSuccess(SettingResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            tv_khmoney.setText(model.getData().getCreateAccountAmount());
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    /**
     * 支付
     */
    private void monipay() {
        Map<String, String> params = new HashMap<>();
        params.put("payType", paytype);
        params.put("token", preferences.getString("token", ""));
        showProgressDialog();
        addSubscription(apiStores.PayForRegister(params),
                new ApiCallback<PayForRegisterResult>() {

                    @Override
                    public void onSuccess(PayForRegisterResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            if (paytype.equals("2")) {
                                zfbpay(model.getData().getContent());
                            } else {
                                wxpay(model);
                            }
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    private void wxpay(PayForRegisterResult model) {
        api.registerApp(model.getData().getAppId());
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (!isPaySupported) {
            Toast.makeText(YanzhengActivity.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(YanzhengActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try {
            PayReq request = new PayReq();

            request.appId = model.getData().getAppId();

            request.partnerId = model.getData().getPartnerId();

            request.prepayId = model.getData().getPrepayId();

            request.packageValue = "Sign=WXPay";

            request.nonceStr = model.getData().getNoncestr();

            request.timeStamp = model.getData().getTimestamp();

            request.sign = model.getData().getSign();

            api.sendReq(request);

        } catch (Exception e) {
            Toast.makeText(YanzhengActivity.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void wxpayresult(Integer progress) {
        if (progress == 0) {//支付成功
            Toast.makeText(YanzhengActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
            paysuccesschangestate();
        } else {
            Toast.makeText(YanzhengActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void zfbpay(final String orderinfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(YanzhengActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(YanzhengActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        paysuccesschangestate();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(YanzhengActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_yanzheng_wx:
                if (isChecked) {
                    cb_zfb.setChecked(false);
                    paytype = "1";
                } else {
                    cb_zfb.setChecked(true);
                    paytype = "2";
                }
                break;
            case R.id.cb_yanzheng_zfb:
                if (isChecked) {
                    cb_wx.setChecked(false);
                    paytype = "2";
                } else {
                    cb_wx.setChecked(true);
                    paytype = "1";
                }
                break;
        }
    }

    class EditTextWatcher implements TextWatcher {

        public void afterTextChanged(Editable edt) {

            //手机号不为空，且为11位
            if (!TextUtils.isNullorEmpty(et_name.getText().toString()) && !TextUtils.isNullorEmpty(et_idnum.getText().toString())) {
                btn_sure.setEnabled(true);
            } else {
                btn_sure.setEnabled(false);
            }
        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 1) {
            et_yanzheng_city.setText(data.getStringExtra("cityname"));
        }
    }

    class EditTextWatcher1 implements TextWatcher {

        public void afterTextChanged(Editable edt) {

            //手机号不为空，且为11位
            if (!TextUtils.isNullorEmpty(et_name.getText().toString()) && et_name.getText().toString().length() == 6) {

            } else if (et_name.getText().toString().length() > 6) {
                et_name.setText(et_name.getText().toString().substring(0, 6));
                et_name.setSelection(6);
                toastShow("密码需设定为6位数字");
            }
        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

    }

    class EditTextWatcher2 implements TextWatcher {

        public void afterTextChanged(Editable edt) {

            //手机号不为空，且为11位
            if (!TextUtils.isNullorEmpty(et_idnum.getText().toString()) && et_idnum.getText().toString().length() == 6) {

            } else if (et_idnum.getText().toString().length() > 6) {
                et_idnum.setText(et_idnum.getText().toString().substring(0, 6));
                et_idnum.setSelection(6);
                toastShow("密码需设定为6位数字");
            }
        }

        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

        public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        }

    }

    private void getWZMsg() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("type", "9");
        showProgressDialog();
        addSubscription(apiStores.GetInformationzcxy(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            Intent i = new Intent(YanzhengActivity.this, TotalWebActivity.class);
                            i.putExtra("title", "骑行充值协议");
                            i.putExtra("url", model.getData());
                            startActivity(i);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
}
